#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
UI组件模块
定义各种UI组件和页面
"""

from PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QTextEdit, QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox, QLineEdit, QDateEdit, QApplication, QDialog
from PyQt5.QtCore import Qt, QDate
from lottery_rules import get_lottery_rule, handle_save_button, handle_save_user_numbers

class LotteryHistoryWidget(QWidget):
    """
    彩票历史记录组件
    """
    def __init__(self):
        super().__init__()
        self.init_ui()
    
    def init_ui(self):
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        # 标题
        title = QLabel("双色球开奖号码录入")
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet("font-size: 18px; font-weight: bold; margin: 10px;")
        layout.addWidget(title)
        
        # 开奖日期输入
        date_layout = QHBoxLayout()
        date_label = QLabel("开奖日期:")
        self.date_input = QDateEdit()
        self.date_input.setDate(QDate.currentDate())
        self.date_input.setDisplayFormat("yyyy-MM-dd")
        date_layout.addWidget(date_label)
        date_layout.addWidget(self.date_input)
        date_layout.addStretch()
        layout.addLayout(date_layout)
        
        # 开奖号码输入
        numbers_layout = QHBoxLayout()  # 改为水平布局
        numbers_label = QLabel("开奖号码:")
        self.winning_numbers_input = QLineEdit()
        self.winning_numbers_input.setPlaceholderText("例如: 1,2,3,4,5,6+7")
        self.winning_numbers_input.setFixedWidth(150)  # 限制输入框宽度
        numbers_layout.addWidget(numbers_label)
        numbers_layout.addWidget(self.winning_numbers_input)
        
        # 保存按钮放在输入框后面
        save_btn = QPushButton("保存")
        save_btn.setFixedWidth(60)  # 设置按钮固定宽度
        save_btn.clicked.connect(self.save_winning_numbers)
        numbers_layout.addWidget(save_btn)
        
        layout.addLayout(numbers_layout)
        
        # 历史记录表格显示区域
        self.history_table = QTableWidget()
        self.history_table.setColumnCount(3)
        self.history_table.setHorizontalHeaderLabels(["开奖日期", "开奖号码", "操作"])
        self.history_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.history_table.setAlternatingRowColors(True)
        layout.addWidget(self.history_table)
        
        # 操作按钮
        button_layout = QHBoxLayout()
        refresh_btn = QPushButton("刷新")
        refresh_btn.setFixedWidth(60)  # 设置按钮固定宽度
        refresh_btn.clicked.connect(self.refresh_history)
        button_layout.addWidget(refresh_btn)
        
        layout.addLayout(button_layout)
        
        # 初始化时加载数据
        self.refresh_history()
    
    def save_winning_numbers(self):
        # 从主窗口获取数据管理器来保存开奖号码
        from main import MainWindow
        main_window = None
        for widget in self.window().findChildren(QWidget):
            if isinstance(widget, MainWindow):
                main_window = widget
                break
                
        # 确保我们总是能获取到主窗口实例
        if not main_window:
            # 如果通过查找找不到，尝试直接获取
            main_window = self.window()
            # 检查是否是MainWindow实例
            if not hasattr(main_window, 'data_manager'):
                main_window = None
        
        # 解析输入的开奖号码
        numbers_text = self.winning_numbers_input.text().strip()
        if not numbers_text:
            QMessageBox.warning(self, "输入错误", "请输入开奖号码")
            return
            
        try:
            # 解析号码格式，支持中英文逗号
            numbers_text = numbers_text.replace('，', ',')  # 将中文逗号替换为英文逗号
            if "+" not in numbers_text:
                raise ValueError("号码格式错误")
                
            parts = numbers_text.split("+")
            if len(parts) != 2:
                raise ValueError("号码格式错误")
                
            red_balls_str = parts[0]
            blue_ball_str = parts[1]
            
            red_balls = [int(x.strip()) for x in red_balls_str.split(",")]
            blue_ball = int(blue_ball_str.strip())
            
            if len(red_balls) != 6:
                raise ValueError("红球号码必须是6个")
                
            # 检查号码范围
            for num in red_balls:
                if num < 1 or num > 33:
                    raise ValueError("红球号码必须在1-33之间")
                    
            if blue_ball < 1 or blue_ball > 16:
                raise ValueError("蓝球号码必须在1-16之间")
            
            # 保存开奖号码到文件（使用新的保存方法）
            date = self.date_input.date().toString("yyyy-MM-dd")
            winning_numbers = [red_balls, blue_ball]
            handle_save_button("double_color_ball", winning_numbers, date)
            
            # 如果有主窗口，保存开奖号码到历史记录
            if main_window and hasattr(main_window, 'data_manager'):
                result = main_window.data_manager.add_lottery_result(
                    "double_color_ball", 
                    date, 
                    [red_balls, blue_ball]
                )
            
            QMessageBox.information(self, "保存成功", "开奖号码保存成功")
            self.winning_numbers_input.clear()
            self.refresh_history()  # 保存后刷新显示
            
        except ValueError as e:
            QMessageBox.critical(self, "输入错误", f"号码格式错误: {str(e)}")
        except Exception as e:
            QMessageBox.critical(self, "保存失败", f"保存开奖号码时发生错误: {str(e)}")
    
    def refresh_history(self):
        # 从主窗口获取数据管理器来加载历史记录
        from main import MainWindow
        from data_manager import DataManager
        main_window = None
        for widget in self.window().findChildren(QWidget):
            if isinstance(widget, MainWindow):
                main_window = widget
                break
                
        # 如果找不到主窗口，使用默认的数据管理器
        if main_window:
            print(f"通过主窗口加载数据: {main_window}")
            history = main_window.data_manager.load_lottery_history()
        else:
            # 创建默认数据管理器实例来加载数据
            print("通过默认数据管理器加载数据")
            data_manager = DataManager()
            print(f"数据目录: {data_manager.data_dir}")
            history = data_manager.load_lottery_history()
            print(f"加载到的历史记录数量: {len(history)}")
            
        # 只显示双色球记录
        dcb_history = [item for item in history if item["type"] == "double_color_ball"]
        print(f"双色球记录数量: {len(dcb_history)}")
        
        # 设置行数
        self.history_table.setRowCount(len(dcb_history))
        
        for row, item in enumerate(dcb_history):
            # 设置开奖日期为可编辑，并使用自定义的日期编辑器
            date_item = QTableWidgetItem(item["date"])
            date_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled)
            self.history_table.setItem(row, 0, date_item)
            
            # 设置开奖号码为可编辑
            numbers_str = ",".join(map(str, item["numbers"][0])) + "+" + str(item["numbers"][1])
            numbers_item = QTableWidgetItem(numbers_str)
            numbers_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled)
            self.history_table.setItem(row, 1, numbers_item)
            
            # 添加保存和删除按钮
            button_widget = QWidget()
            button_layout = QHBoxLayout(button_widget)
            button_layout.setContentsMargins(0, 0, 0, 0)
            
            save_btn = QPushButton("保存")
            delete_btn = QPushButton("删除")
            
            # 设置按钮固定宽度
            save_btn.setFixedWidth(50)
            delete_btn.setFixedWidth(50)
            
            # 默认保存按钮不可用
            save_btn.setEnabled(False)
            
            # 连接按钮信号
            save_btn.clicked.connect(lambda checked, r=row: self.save_history_editing(r))
            delete_btn.clicked.connect(lambda checked, r=row: self.delete_record_by_row(r))
            
            button_layout.addWidget(save_btn)
            button_layout.addWidget(delete_btn)
            
            self.history_table.setCellWidget(row, 2, button_widget)
            # 保存按钮引用以便后续操作
            button_widget.save_btn = save_btn
        
        # 连接表格单元格更改信号
        self.history_table.cellChanged.connect(self.on_history_cell_changed)
        # 连接表格单元格双击信号，用于日期选择
        self.history_table.cellDoubleClicked.connect(self.on_history_cell_double_clicked)
    
    def on_history_cell_changed(self, row, column):
        """处理开奖历史表格单元格更改事件"""
        # 点亮保存按钮
        button_widget = self.history_table.cellWidget(row, 2)
        if button_widget and hasattr(button_widget, 'save_btn'):
            button_widget.save_btn.setEnabled(True)
        
        # 注意：这里不直接保存数据，仅点亮保存按钮
        # 实际保存由save_history_editing方法处理
    
    def save_history_editing(self, row):
        """保存行编辑结果"""
        # 直接使用DataManager而不是依赖主窗口
        from data_manager import DataManager
        data_manager = DataManager()
        
        try:
            # 获取当前行的数据
            date_item = self.history_table.item(row, 0)
            numbers_item = self.history_table.item(row, 1)
            
            if not date_item or not numbers_item:
                return
                
            date = date_item.text()
            numbers_text = numbers_item.text()
            
            # 解析号码
            numbers_text = numbers_text.replace('，', ',')
            if "+" not in numbers_text:
                raise ValueError("号码格式错误")
                
            parts = numbers_text.split("+")
            if len(parts) != 2:
                raise ValueError("号码格式错误")
                
            red_balls_str = parts[0]
            blue_ball_str = parts[1]
            
            red_balls = [int(x.strip()) for x in red_balls_str.split(",")]
            blue_ball = int(blue_ball_str.strip())
            
            if len(red_balls) != 6:
                raise ValueError("红球号码必须是6个")
                
            # 检查号码范围
            for num in red_balls:
                if num < 1 or num > 33:
                    raise ValueError("红球号码必须在1-33之间")
                    
            if blue_ball < 1 or blue_ball > 16:
                raise ValueError("蓝球号码必须在1-16之间")
            
            # 获取所有历史记录
            history = data_manager.load_lottery_history()
            
            # 查找并更新对应的记录
            for item in history:
                if item["type"] == "double_color_ball" and item["date"] == date:
                    item["numbers"] = [red_balls, blue_ball]
                    break
            
            # 保存更新后的数据
            data_manager.save_lottery_history(history)
            
            # 禁用保存按钮
            button_widget = self.history_table.cellWidget(row, 2)
            if button_widget and hasattr(button_widget, 'save_btn'):
                button_widget.save_btn.setEnabled(False)
                
            QMessageBox.information(self, "保存成功", "开奖记录保存成功")
            
        except ValueError as e:
            QMessageBox.critical(self, "输入错误", f"号码格式错误: {str(e)}")
        except Exception as e:
            QMessageBox.critical(self, "保存失败", f"保存开奖记录时发生错误: {str(e)}")
    
    def on_date_cell_changed(self, row, column, date_edit):
        """处理日期单元格更改事件"""
        from PyQt5.QtCore import QDate
        
        # 获取新的日期值
        new_date = date_edit.date().toString("yyyy-MM-dd")
        
        # 更新表格单元格的显示内容
        date_item = QTableWidgetItem(new_date)
        date_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled)
        self.history_table.removeCellWidget(row, column)
        self.history_table.setItem(row, column, date_item)
        
        # 点亮保存按钮而不是直接保存
        button_widget = self.history_table.cellWidget(row, 2)
        if button_widget and hasattr(button_widget, 'save_btn'):
            button_widget.save_btn.setEnabled(True)
    
    def on_history_cell_double_clicked(self, row, column):
        """处理开奖历史表格单元格双击事件，用于日期选择"""
        if column == 0:  # 如果是日期列
            from PyQt5.QtWidgets import QDateEdit
            from PyQt5.QtCore import QDate
            
            # 获取当前日期值
            date_item = self.history_table.item(row, column)
            if date_item:
                current_date = date_item.text()
                try:
                    # 创建日期编辑控件
                    date_edit = QDateEdit()
                    date_edit.setDisplayFormat("yyyy-MM-dd")
                    date_edit.setDate(QDate.fromString(current_date, "yyyy-MM-dd"))
                    date_edit.setCalendarPopup(True)  # 启用日历弹窗
                    
                    # 将日期编辑控件设置为表格单元格的控件
                    self.history_table.setCellWidget(row, column, date_edit)
                    
                    # 连接日期更改信号
                    date_edit.dateChanged.connect(
                        lambda: self.on_date_cell_changed(row, column, date_edit)
                    )
                except Exception as e:
                    print(f"日期格式错误: {e}")
    
    def delete_record(self, date):
        # 使用DataManager直接处理数据而不是依赖主窗口
        from data_manager import DataManager
        data_manager = DataManager()
        
        history = data_manager.load_lottery_history()
        # 过滤掉要删除的记录
        new_history = [item for item in history if not (item["type"] == "double_color_ball" and item["date"] == date)]
        data_manager.save_lottery_history(new_history)
        self.refresh_history()
        QMessageBox.information(self, "删除成功", "开奖记录删除成功")
    
    def delete_record_by_row(self, row):
        """根据行号删除记录"""
        # 获取要删除的记录的日期
        date_item = self.history_table.item(row, 0)
        if not date_item:
            return
            
        date = date_item.text()
        self.delete_record(date)

class UserTicketManagerWidget(QWidget):
    """
    用户号码管理组件
    """
    def __init__(self):
        super().__init__()
        self.init_ui()
    
    def init_ui(self):
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        # 标题
        title = QLabel("双色球用户号码管理")
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet("font-size: 18px; font-weight: bold; margin: 10px;")
        layout.addWidget(title)
        
        # 购买日期输入
        date_layout = QHBoxLayout()
        date_label = QLabel("购买日期:")
        self.date_input = QDateEdit()
        self.date_input.setDate(QDate.currentDate())
        self.date_input.setDisplayFormat("yyyy-MM-dd")
        date_layout.addWidget(date_label)
        date_layout.addWidget(self.date_input)
        date_layout.addStretch()
        layout.addLayout(date_layout)
        
        # 号码输入区域
        input_layout = QHBoxLayout()  # 改为水平布局
        input_label = QLabel("号码:")
        self.ticket_input = QLineEdit()
        self.ticket_input.setPlaceholderText("例如: 1,2,3,4,5,6+7")
        self.ticket_input.setFixedWidth(150)  # 限制输入框宽度
        input_layout.addWidget(input_label)
        input_layout.addWidget(self.ticket_input)
        
        # 保存按钮放在输入框后面
        save_btn = QPushButton("保存")
        save_btn.setFixedWidth(60)  # 设置按钮固定宽度
        save_btn.clicked.connect(self.save_tickets)
        input_layout.addWidget(save_btn)
        
        layout.addLayout(input_layout)
        
        # 用户号码表格显示
        self.ticket_table = QTableWidget()
        self.ticket_table.setColumnCount(4)
        self.ticket_table.setHorizontalHeaderLabels(["购买日期", "号码", "操作", "中奖结果"])
        self.ticket_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.ticket_table.setAlternatingRowColors(True)
        layout.addWidget(self.ticket_table)
        
        # 操作按钮
        button_layout = QHBoxLayout()
        match_btn = QPushButton("匹配开奖")
        match_btn.setFixedWidth(80)  # 设置按钮固定宽度
        match_btn.clicked.connect(self.match_lottery)
        button_layout.addWidget(match_btn)
        
        refresh_btn = QPushButton("刷新")
        refresh_btn.setFixedWidth(60)  # 设置按钮固定宽度
        refresh_btn.clicked.connect(self.refresh_ticket_table)
        button_layout.addWidget(refresh_btn)
        
        layout.addLayout(button_layout)
        
        # 初始化时加载数据
        self.refresh_ticket_table()
    
    def save_tickets(self):
        # 从主窗口获取数据管理器来保存用户号码
        from main import MainWindow
        from data_manager import DataManager
        main_window = None
        for widget in self.window().findChildren(QWidget):
            if isinstance(widget, MainWindow):
                main_window = widget
                break
                
        print(f"开始保存用户号码，找到主窗口: {main_window is not None}")
        
        # 解析输入的票数据
        numbers_text = self.ticket_input.text().strip()
        print(f"输入的号码文本: {numbers_text}")
        
        if not numbers_text:
            QMessageBox.warning(self, "输入错误", "请输入彩票号码")
            return
            
        try:
            # 解析号码格式，支持中英文逗号
            numbers_text = numbers_text.replace('，', ',')  # 将中文逗号替换为英文逗号
            if "+" not in numbers_text:
                raise ValueError("号码格式错误")
                
            parts = numbers_text.split("+")
            if len(parts) != 2:
                raise ValueError("号码格式错误")
                
            red_balls_str = parts[0]
            blue_ball_str = parts[1]
            
            red_balls = [int(x.strip()) for x in red_balls_str.split(",")]
            blue_ball = int(blue_ball_str.strip())
            
            if len(red_balls) != 6:
                raise ValueError("红球号码必须是6个")
                
            # 检查号码范围
            for num in red_balls:
                if num < 1 or num > 33:
                    raise ValueError("红球号码必须在1-33之间")
                    
            if blue_ball < 1 or blue_ball > 16:
                raise ValueError("蓝球号码必须在1-16之间")
            
            # 保存用户号码到文件（使用新的保存方法）
            date = self.date_input.date().toString("yyyy-MM-dd")
            user_numbers = [red_balls, blue_ball]
            print(f"准备保存号码: 日期={date}, 号码={user_numbers}")
            
            handle_save_user_numbers("double_color_ball", user_numbers, date)
            
            # 获取当前用户票数据
            if main_window:
                tickets = main_window.data_manager.load_user_tickets()
            else:
                # 如果找不到主窗口，使用默认的数据管理器
                data_manager = DataManager()
                tickets = data_manager.load_user_tickets()
            print(f"加载现有票数据，共 {len(tickets)} 条记录")
            
            # 添加新票
            new_ticket = {
                "type": "double_color_ball",
                "date": date,
                "numbers": [red_balls, blue_ball]
            }
            tickets.append(new_ticket)
            
            # 保存用户票数据
            if main_window:
                main_window.data_manager.save_user_tickets(tickets)
            else:
                # 如果找不到主窗口，使用默认的数据管理器
                data_manager = DataManager()
                data_manager.save_user_tickets(tickets)
            print("用户号码保存成功")
            
            QMessageBox.information(self, "保存成功", "号码保存成功")
            self.ticket_input.clear()
            self.refresh_ticket_table()  # 保存后刷新显示
            
        except ValueError as e:
            print(f"号码格式错误: {e}")
            QMessageBox.critical(self, "输入错误", f"号码格式错误: {str(e)}")
        except Exception as e:
            print(f"保存号码时发生错误: {e}")
            QMessageBox.critical(self, "保存失败", f"保存号码时发生错误: {str(e)}")
    
    def refresh_ticket_table(self):
        # 从主窗口获取数据管理器来加载用户号码
        from main import MainWindow
        from data_manager import DataManager
        main_window = None
        for widget in self.window().findChildren(QWidget):
            if isinstance(widget, MainWindow):
                main_window = widget
                break
                
        # 如果找不到主窗口，使用默认的数据管理器
        if main_window:
            print(f"通过主窗口加载用户票数据: {main_window}")
            tickets = main_window.data_manager.load_user_tickets()
        else:
            # 创建默认数据管理器实例来加载数据
            print("通过默认数据管理器加载用户票数据")
            data_manager = DataManager()
            print(f"数据目录: {data_manager.data_dir}")
            tickets = data_manager.load_user_tickets()
            print(f"加载到的用户票数量: {len(tickets)}")
            
        # 只显示双色球记录
        dcb_tickets = [ticket for ticket in tickets if ticket["type"] == "double_color_ball"]
        print(f"双色球票数量: {len(dcb_tickets)}")
        
        self.ticket_table.setRowCount(len(dcb_tickets))
        
        for row, ticket in enumerate(dcb_tickets):
            # 设置购买日期为可编辑，并使用自定义的日期编辑器
            date_item = QTableWidgetItem(ticket["date"])
            date_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled)
            self.ticket_table.setItem(row, 0, date_item)
            
            # 格式化显示号码
            numbers_str = ",".join(map(str, ticket["numbers"][0])) + "+" + str(ticket["numbers"][1])
            numbers_item = QTableWidgetItem(numbers_str)
            numbers_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled)
            self.ticket_table.setItem(row, 1, numbers_item)
            
            # 添加保存和删除按钮
            button_widget = QWidget()
            button_layout = QHBoxLayout(button_widget)
            button_layout.setContentsMargins(0, 0, 0, 0)
            
            save_btn = QPushButton("保存")
            delete_btn = QPushButton("删除")
            
            # 设置按钮固定宽度
            save_btn.setFixedWidth(50)
            delete_btn.setFixedWidth(50)
            
            # 默认保存按钮不可用
            save_btn.setEnabled(False)
            
            # 连接按钮信号
            save_btn.clicked.connect(lambda checked, r=row: self.save_ticket_editing(r))
            delete_btn.clicked.connect(lambda checked, r=row: self.delete_ticket_by_row(r))
            
            button_layout.addWidget(save_btn)
            button_layout.addWidget(delete_btn)
            
            self.ticket_table.setCellWidget(row, 2, button_widget)
            # 保存按钮引用以便后续操作
            button_widget.save_btn = save_btn
            
            # 中奖结果显示
            self.ticket_table.setItem(row, 3, QTableWidgetItem("未匹配"))
        
        # 连接表格单元格双击信号，用于日期选择
        self.ticket_table.cellDoubleClicked.connect(self.on_ticket_cell_double_clicked)
        # 连接单元格更改信号
        self.ticket_table.cellChanged.connect(self.on_ticket_cell_changed)
    
    def save_ticket_editing(self, row):
        """保存票务行编辑结果"""
        # 禁用保存按钮
        button_widget = self.ticket_table.cellWidget(row, 2)
        if button_widget and hasattr(button_widget, 'save_btn'):
            button_widget.save_btn.setEnabled(False)
        
        # 直接保存数据而不是触发另一个事件
        self._save_ticket_data(row)

    def _save_ticket_data(self, row):
        """实际保存票务数据"""
        from data_manager import DataManager
        data_manager = DataManager()
        
        # 获取更改后的数据
        date_item = self.ticket_table.item(row, 0)
        numbers_item = self.ticket_table.item(row, 1)
        
        if not date_item or not numbers_item:
            return
            
        new_date = date_item.text()
        numbers_text = numbers_item.text()
        
        try:
            # 解析号码格式
            numbers_text = numbers_text.replace('，', ',')
            if "+" not in numbers_text:
                raise ValueError("号码格式错误")
                
            parts = numbers_text.split("+")
            if len(parts) != 2:
                raise ValueError("号码格式错误")
                
            red_balls_str = parts[0]
            blue_ball_str = parts[1]
            
            red_balls = [int(x.strip()) for x in red_balls_str.split(",")]
            blue_ball = int(blue_ball_str.strip())
            
            if len(red_balls) != 6:
                raise ValueError("红球号码必须是6个")
                
            # 检查号码范围
            for num in red_balls:
                if num < 1 or num > 33:
                    raise ValueError("红球号码必须在1-33之间")
                    
            if blue_ball < 1 or blue_ball > 16:
                raise ValueError("蓝球号码必须在1-16之间")
            
            # 获取所有票数据并更新对应记录
            tickets = data_manager.load_user_tickets()
            
            # 查找并更新记录
            for ticket in tickets:
                if ticket["type"] == "double_color_ball" and ticket["date"] == new_date:
                    ticket["numbers"] = [red_balls, blue_ball]
                    break
            
            # 保存更新后的数据
            data_manager.save_user_tickets(tickets)
                
        except ValueError as e:
            QMessageBox.critical(self, "输入错误", f"号码格式错误: {str(e)}")
            # 恢复原始数据
            self.ticket_table.cellChanged.disconnect(self.on_ticket_cell_changed)
            self.refresh_ticket_table()
            self.ticket_table.cellChanged.connect(self.on_ticket_cell_changed)

    def on_ticket_cell_changed(self, row, column):
        """处理用户票表格单元格更改事件"""
        # 点亮保存按钮
        button_widget = self.ticket_table.cellWidget(row, 2)
        if button_widget and hasattr(button_widget, 'save_btn'):
            button_widget.save_btn.setEnabled(True)
        
        # 不再直接保存数据，只点亮保存按钮
    
    def on_ticket_cell_double_clicked(self, row, column):
        """处理用户票表格单元格双击事件，用于日期选择"""
        if column == 0:  # 如果是日期列
            from PyQt5.QtWidgets import QDateEdit
            from PyQt5.QtCore import QDate
            
            # 获取当前日期值
            date_item = self.ticket_table.item(row, column)
            if date_item:
                current_date = date_item.text()
                try:
                    # 创建日期编辑控件
                    date_edit = QDateEdit()
                    date_edit.setDisplayFormat("yyyy-MM-dd")
                    date_edit.setDate(QDate.fromString(current_date, "yyyy-MM-dd"))
                    date_edit.setCalendarPopup(True)  # 启用日历弹窗
                    
                    # 将日期编辑控件设置为表格单元格的控件
                    self.ticket_table.setCellWidget(row, column, date_edit)
                    
                    # 连接日期更改信号
                    date_edit.dateChanged.connect(
                        lambda: self.on_ticket_date_cell_changed(row, column, date_edit)
                    )
                except Exception as e:
                    print(f"日期格式错误: {e}")
    
    def on_ticket_date_cell_changed(self, row, column, date_edit):
        """处理用户票日期单元格更改事件"""
        from PyQt5.QtCore import QDate
        
        # 获取新的日期值
        new_date = date_edit.date().toString("yyyy-MM-dd")
        
        # 更新表格单元格的显示内容
        date_item = QTableWidgetItem(new_date)
        date_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled)
        self.ticket_table.removeCellWidget(row, column)
        self.ticket_table.setItem(row, column, date_item)
        
        # 触发数据保存
        self.on_ticket_cell_changed(row, column)
    
    def delete_ticket(self, date):
        # 使用DataManager直接处理数据而不是依赖主窗口
        from data_manager import DataManager
        data_manager = DataManager()
        
        tickets = data_manager.load_user_tickets()
        # 过滤掉要删除的记录（简单按日期过滤，实际应用中可能需要更精确的标识）
        new_tickets = [ticket for ticket in tickets if not (ticket["type"] == "double_color_ball" and ticket["date"] == date)]
        data_manager.save_user_tickets(new_tickets)
        self.refresh_ticket_table()
        QMessageBox.information(self, "删除成功", "用户号码删除成功")
    
    def delete_ticket_by_row(self, row):
        """根据行号删除票"""
        # 获取要删除的记录的日期
        date_item = self.ticket_table.item(row, 0)
        if not date_item:
            return
            
        date = date_item.text()
        self.delete_ticket(date)
    
    def match_lottery(self):
        # 使用DataManager直接处理数据而不是依赖主窗口
        from data_manager import DataManager
        from matcher import NumberMatcher
        
        data_manager = DataManager()
        matcher = NumberMatcher()
        
        user_tickets = data_manager.load_user_tickets()
        lottery_history = data_manager.load_lottery_history()
        
        # 只处理双色球
        dcb_tickets = [ticket for ticket in user_tickets if ticket["type"] == "double_color_ball"]
        dcb_history = [history for history in lottery_history if history["type"] == "double_color_ball"]
        
        # 修复匹配逻辑：确保有数据才进行匹配
        if not dcb_tickets or not dcb_history:
            QMessageBox.information(self, "匹配结果", "没有足够的数据进行匹配，请确保已录入开奖历史和用户号码")
            return
            
        results = matcher.match_tickets(dcb_tickets, dcb_history)
        
        # 创建结果对话框
        result_dialog = QMessageBox(self)
        result_dialog.setWindowTitle("匹配结果")
        result_dialog.setText("双色球中奖匹配结果")
        
        # 显示匹配结果
        result_text = ""
        for result in results:
            if "error" in result:
                result_text += f"错误: {result['error']}\n"
            else:
                date = result.get('ticket_date', '未知日期')
                prize_name = result['prize_info']['name']
                if result['is_winning']:
                    result_text += f"日期 {date}: 中奖 - {prize_name}\n"
                else:
                    result_text += f"日期 {date}: 未中奖\n"
        
        if not results:
            result_text = "没有可匹配的记录"
            
        result_dialog.setDetailedText(result_text)
        result_dialog.exec_()
        
        # 更新表格中的中奖结果显示
        self.refresh_ticket_table_with_results(results)

    # 添加缺失的方法来更新中奖结果显示
    def refresh_ticket_table_with_results(self, results):
        """
        根据匹配结果更新表格中的中奖结果显示
        """
        for row in range(self.ticket_table.rowCount()):
            # 获取当前行的日期
            date_item = self.ticket_table.item(row, 0)
            if not date_item:
                continue
                
            current_date = date_item.text()
            
            # 查找匹配的结果
            result_found = False
            for result in results:
                if result.get('ticket_date') == current_date:
                    # 更新中奖结果显示
                    prize_item = self.ticket_table.item(row, 3)
                    if prize_item:
                        if "error" in result:
                            prize_item.setText("错误")
                        else:
                            prize_name = result['prize_info']['name']
                            prize_item.setText(prize_name if result['is_winning'] else "未中奖")
                    result_found = True
                    break
            
            # 如果没有找到匹配结果，保持原状或设置为"未匹配"
            if not result_found:
                prize_item = self.ticket_table.item(row, 3)
                if prize_item and prize_item.text() == "":
                    prize_item.setText("未匹配")

class LotteryDetailsWidget(QWidget):
    """
    彩票详情组件
    """
    def __init__(self):
        super().__init__()
        self.init_ui()
    
    def init_ui(self):
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        # 标题
        title = QLabel("双色球规则说明")
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet("font-size: 18px; font-weight: bold; margin: 10px;")
        layout.addWidget(title)
        
        # 规则说明
        rules_label = QLabel("双色球规则:")
        rules_label.setStyleSheet("font-size: 14px; font-weight: bold; margin-top: 10px;")
        layout.addWidget(rules_label)
        
        self.rules_display = QTextEdit()
        self.rules_display.setReadOnly(True)
        self.rules_display.setText("双色球规则：6个红球(1-33)+1个蓝球(1-16)\n\n"
                                  "开奖时间：每周二、四、日晚上\n\n"
                                  "奖项设置：\n"
                                  "一等奖：6个红球+1个蓝球\n"
                                  "二等奖：6个红球\n"
                                  "三等奖：5个红球+1个蓝球\n"
                                  "四等奖：5个红球或4个红球+1个蓝球\n"
                                  "五等奖：4个红球或3个红球+1个蓝球\n"
                                  "六等奖：1个蓝球")
        layout.addWidget(self.rules_display)
        
        # 中奖查询说明
        instruction_label = QLabel("使用说明:")
        instruction_label.setStyleSheet("font-size: 14px; font-weight: bold; margin-top: 10px;")
        layout.addWidget(instruction_label)
        
        instruction_text = QTextEdit()
        instruction_text.setReadOnly(True)
        instruction_text.setText("1. 在'开奖历史'标签页中录入开奖号码\n"
                                "2. 在'号码管理'标签页中录入您的购买号码\n"
                                "3. 点击'匹配开奖'按钮查看中奖结果")
        layout.addWidget(instruction_text)
        
        # 添加操作按钮
        button_layout = QHBoxLayout()
        close_btn = QPushButton("关闭")
        close_btn.clicked.connect(self.close)
        button_layout.addWidget(close_btn)
        layout.addLayout(button_layout)

class LotteryManagementWidget(QWidget):
    """
    彩票管理组件 - 整合开奖号码和用户号码管理
    """
    def __init__(self):
        super().__init__()
        self.init_ui()
    
    def init_ui(self):
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        # 标题
        title = QLabel("双色球号码管理")
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet("font-size: 18px; font-weight: bold; margin: 10px;")
        layout.addWidget(title)
        
        # 开奖号码录入区域
        winning_numbers_group = QWidget()
        winning_numbers_layout = QVBoxLayout(winning_numbers_group)
        winning_numbers_layout.setContentsMargins(10, 10, 10, 10)
        
        winning_title = QLabel("开奖号码录入")
        winning_title.setStyleSheet("font-size: 14px; font-weight: bold;")
        winning_numbers_layout.addWidget(winning_title)
        
        # 开奖日期和号码输入
        winning_input_layout = QHBoxLayout()
        date_label = QLabel("开奖日期:")
        self.winning_date_input = QDateEdit()
        self.winning_date_input.setDate(QDate.currentDate())
        self.winning_date_input.setDisplayFormat("yyyy-MM-dd")
        winning_input_layout.addWidget(date_label)
        winning_input_layout.addWidget(self.winning_date_input)
        
        numbers_label = QLabel("开奖号码:")
        self.winning_numbers_input = QLineEdit()
        self.winning_numbers_input.setPlaceholderText("例如: 1,2,3,4,5,6+7")
        self.winning_numbers_input.setFixedWidth(150)
        winning_input_layout.addWidget(numbers_label)
        winning_input_layout.addWidget(self.winning_numbers_input)
        
        save_winning_btn = QPushButton("保存")
        save_winning_btn.setFixedWidth(60)
        save_winning_btn.clicked.connect(self.save_winning_numbers)
        winning_input_layout.addWidget(save_winning_btn)
        winning_input_layout.addStretch()
        
        winning_numbers_layout.addLayout(winning_input_layout)
        layout.addWidget(winning_numbers_group)
        
        # 用户号码录入区域
        user_numbers_group = QWidget()
        user_numbers_layout = QVBoxLayout(user_numbers_group)
        user_numbers_layout.setContentsMargins(10, 10, 10, 10)
        
        user_title = QLabel("用户号码录入")
        user_title.setStyleSheet("font-size: 14px; font-weight: bold;")
        user_numbers_layout.addWidget(user_title)
        
        # 购买日期和号码输入
        user_input_layout = QHBoxLayout()
        user_date_label = QLabel("购买日期:")
        self.user_date_input = QDateEdit()
        self.user_date_input.setDate(QDate.currentDate())
        self.user_date_input.setDisplayFormat("yyyy-MM-dd")
        user_input_layout.addWidget(user_date_label)
        user_input_layout.addWidget(self.user_date_input)
        
        user_numbers_label = QLabel("号码:")
        self.user_numbers_input = QLineEdit()
        self.user_numbers_input.setPlaceholderText("例如: 1,2,3,4,5,6+7")
        self.user_numbers_input.setFixedWidth(150)
        user_input_layout.addWidget(user_numbers_label)
        user_input_layout.addWidget(self.user_numbers_input)
        
        save_user_btn = QPushButton("保存")
        save_user_btn.setFixedWidth(60)
        save_user_btn.clicked.connect(self.save_user_numbers)
        user_input_layout.addWidget(save_user_btn)
        user_input_layout.addStretch()
        
        user_numbers_layout.addLayout(user_input_layout)
        layout.addWidget(user_numbers_group)
        
        # 数据表格区域
        tables_layout = QHBoxLayout()
        
        # 开奖历史表格
        history_layout = QVBoxLayout()
        history_label = QLabel("开奖历史")
        history_label.setAlignment(Qt.AlignCenter)
        history_layout.addWidget(history_label)
        
        self.history_table = QTableWidget()
        self.history_table.setColumnCount(3)
        self.history_table.setHorizontalHeaderLabels(["开奖日期", "开奖号码", "操作"])
        self.history_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.history_table.setAlternatingRowColors(True)
        history_layout.addWidget(self.history_table)
        tables_layout.addLayout(history_layout)
        
        # 用户号码表格
        user_layout = QVBoxLayout()
        user_label = QLabel("用户号码")
        user_label.setAlignment(Qt.AlignCenter)
        user_layout.addWidget(user_label)
        
        self.user_table = QTableWidget()
        self.user_table.setColumnCount(4)
        self.user_table.setHorizontalHeaderLabels(["购买日期", "号码", "操作", "中奖结果"])
        self.user_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.user_table.setAlternatingRowColors(True)
        user_layout.addWidget(self.user_table)
        tables_layout.addLayout(user_layout)
        
        layout.addLayout(tables_layout)
        
        # 操作按钮
        button_layout = QHBoxLayout()
        match_btn = QPushButton("匹配开奖")
        match_btn.setFixedWidth(80)
        match_btn.clicked.connect(self.match_lottery)
        button_layout.addWidget(match_btn)
        
        refresh_btn = QPushButton("刷新")
        refresh_btn.setFixedWidth(60)
        refresh_btn.clicked.connect(self.refresh_all_tables)
        button_layout.addWidget(refresh_btn)
        button_layout.addStretch()
        
        layout.addLayout(button_layout)
        
        # 初始化时加载数据
        self.refresh_all_tables()
    
    def save_winning_numbers(self):
        # 从主窗口获取数据管理器来保存开奖号码
        from main import MainWindow
        main_window = None
        for widget in self.window().findChildren(QWidget):
            if isinstance(widget, MainWindow):
                main_window = widget
                break
                
        # 确保我们总是能获取到主窗口实例
        if not main_window:
            # 如果通过查找找不到，尝试直接获取
            main_window = self.window()
            # 检查是否是MainWindow实例
            if not hasattr(main_window, 'data_manager'):
                main_window = None
        
        # 解析输入的开奖号码
        numbers_text = self.winning_numbers_input.text().strip()
        if not numbers_text:
            QMessageBox.warning(self, "输入错误", "请输入开奖号码")
            return
            
        try:
            # 解析号码格式，支持中英文逗号
            numbers_text = numbers_text.replace('，', ',')  # 将中文逗号替换为英文逗号
            if "+" not in numbers_text:
                raise ValueError("号码格式错误")
                
            parts = numbers_text.split("+")
            if len(parts) != 2:
                raise ValueError("号码格式错误")
                
            red_balls_str = parts[0]
            blue_ball_str = parts[1]
            
            red_balls = [int(x.strip()) for x in red_balls_str.split(",")]
            blue_ball = int(blue_ball_str.strip())
            
            if len(red_balls) != 6:
                raise ValueError("红球号码必须是6个")
                
            # 检查号码范围
            for num in red_balls:
                if num < 1 or num > 33:
                    raise ValueError("红球号码必须在1-33之间")
                    
            if blue_ball < 1 or blue_ball > 16:
                raise ValueError("蓝球号码必须在1-16之间")
            
            # 保存开奖号码到文件（使用新的保存方法）
            date = self.winning_date_input.date().toString("yyyy-MM-dd")
            winning_numbers = [red_balls, blue_ball]
            handle_save_button("double_color_ball", winning_numbers, date)
            
            # 如果有主窗口，保存开奖号码到历史记录
            if main_window and hasattr(main_window, 'data_manager'):
                result = main_window.data_manager.add_lottery_result(
                    "double_color_ball", 
                    date, 
                    [red_balls, blue_ball]
                )
            
            QMessageBox.information(self, "保存成功", "开奖号码保存成功")
            self.winning_numbers_input.clear()
            self.refresh_history_table()  # 保存后刷新显示
            
        except ValueError as e:
            QMessageBox.critical(self, "输入错误", f"号码格式错误: {str(e)}")
        except Exception as e:
            QMessageBox.critical(self, "保存失败", f"保存开奖号码时发生错误: {str(e)}")
    
    def save_user_numbers(self):
        # 从主窗口获取数据管理器来保存用户号码
        from main import MainWindow
        from data_manager import DataManager
        main_window = None
        for widget in self.window().findChildren(QWidget):
            if isinstance(widget, MainWindow):
                main_window = widget
                break
                
        print(f"开始保存用户号码，找到主窗口: {main_window is not None}")
        
        # 解析输入的票数据
        numbers_text = self.user_numbers_input.text().strip()
        print(f"输入的号码文本: {numbers_text}")
        
        if not numbers_text:
            QMessageBox.warning(self, "输入错误", "请输入彩票号码")
            return
            
        try:
            # 解析号码格式，支持中英文逗号
            numbers_text = numbers_text.replace('，', ',')  # 将中文逗号替换为英文逗号
            if "+" not in numbers_text:
                raise ValueError("号码格式错误")
                
            parts = numbers_text.split("+")
            if len(parts) != 2:
                raise ValueError("号码格式错误")
                
            red_balls_str = parts[0]
            blue_ball_str = parts[1]
            
            red_balls = [int(x.strip()) for x in red_balls_str.split(",")]
            blue_ball = int(blue_ball_str.strip())
            
            if len(red_balls) != 6:
                raise ValueError("红球号码必须是6个")
                
            # 检查号码范围
            for num in red_balls:
                if num < 1 or num > 33:
                    raise ValueError("红球号码必须在1-33之间")
                    
            if blue_ball < 1 or blue_ball > 16:
                raise ValueError("蓝球号码必须在1-16之间")
            
            # 保存用户号码到文件（使用新的保存方法）
            date = self.user_date_input.date().toString("yyyy-MM-dd")
            user_numbers = [red_balls, blue_ball]
            print(f"准备保存号码: 日期={date}, 号码={user_numbers}")
            
            handle_save_user_numbers("double_color_ball", user_numbers, date)
            
            # 获取当前用户票数据
            if main_window:
                tickets = main_window.data_manager.load_user_tickets()
            else:
                # 如果找不到主窗口，使用默认的数据管理器
                data_manager = DataManager()
                tickets = data_manager.load_user_tickets()
            print(f"加载现有票数据，共 {len(tickets)} 条记录")
            
            # 添加新票
            new_ticket = {
                "type": "double_color_ball",
                "date": date,
                "numbers": [red_balls, blue_ball]
            }
            tickets.append(new_ticket)
            
            # 保存用户票数据
            if main_window:
                main_window.data_manager.save_user_tickets(tickets)
            else:
                # 如果找不到主窗口，使用默认的数据管理器
                data_manager = DataManager()
                data_manager.save_user_tickets(tickets)
            print("用户号码保存成功")
            
            QMessageBox.information(self, "保存成功", "号码保存成功")
            self.user_numbers_input.clear()
            self.refresh_user_table()  # 保存后刷新显示
            
        except ValueError as e:
            print(f"号码格式错误: {e}")
            QMessageBox.critical(self, "输入错误", f"号码格式错误: {str(e)}")
        except Exception as e:
            print(f"保存号码时发生错误: {e}")
            QMessageBox.critical(self, "保存失败", f"保存号码时发生错误: {str(e)}")
    
    def refresh_all_tables(self):
        self.refresh_history_table()
        self.refresh_user_table()
    
    def refresh_history_table(self):
        # 从主窗口获取数据管理器来加载历史记录
        from main import MainWindow
        from data_manager import DataManager
        main_window = None
        for widget in self.window().findChildren(QWidget):
            if isinstance(widget, MainWindow):
                main_window = widget
                break
                
        # 如果找不到主窗口，使用默认的数据管理器
        if main_window:
            print(f"通过主窗口加载数据: {main_window}")
            history = main_window.data_manager.load_lottery_history()
        else:
            # 创建默认数据管理器实例来加载数据
            print("通过默认数据管理器加载数据")
            data_manager = DataManager()
            print(f"数据目录: {data_manager.data_dir}")
            history = data_manager.load_lottery_history()
            print(f"加载到的历史记录数量: {len(history)}")
            
        # 只显示双色球记录
        dcb_history = [item for item in history if item["type"] == "double_color_ball"]
        print(f"双色球记录数量: {len(dcb_history)}")
        
        # 设置行数
        self.history_table.setRowCount(len(dcb_history))
        
        for row, item in enumerate(dcb_history):
            # 设置开奖日期为可编辑，并使用自定义的日期编辑器
            date_item = QTableWidgetItem(item["date"])
            date_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled)
            self.history_table.setItem(row, 0, date_item)
            
            # 设置开奖号码为可编辑
            numbers_str = ",".join(map(str, item["numbers"][0])) + "+" + str(item["numbers"][1])
            numbers_item = QTableWidgetItem(numbers_str)
            numbers_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled)
            self.history_table.setItem(row, 1, numbers_item)
            
            # 添加保存和删除按钮
            button_widget = QWidget()
            button_layout = QHBoxLayout(button_widget)
            button_layout.setContentsMargins(0, 0, 0, 0)
            
            save_btn = QPushButton("保存")
            delete_btn = QPushButton("删除")
            
            # 设置按钮固定宽度
            save_btn.setFixedWidth(50)
            delete_btn.setFixedWidth(50)
            
            # 默认保存按钮不可用
            save_btn.setEnabled(False)
            
            # 连接按钮信号
            save_btn.clicked.connect(lambda checked, r=row: self.save_history_editing(r))
            delete_btn.clicked.connect(lambda checked, r=row: self.delete_record_by_row(r))
            
            button_layout.addWidget(save_btn)
            button_layout.addWidget(delete_btn)
            
            self.history_table.setCellWidget(row, 2, button_widget)
            # 保存按钮引用以便后续操作
            button_widget.save_btn = save_btn
        
        # 连接表格单元格更改信号
        self.history_table.cellChanged.connect(self.on_history_cell_changed)
        # 连接表格单元格双击信号，用于日期选择
        self.history_table.cellDoubleClicked.connect(self.on_history_cell_double_clicked)
    
    def refresh_user_table(self):
        # 从主窗口获取数据管理器来加载用户号码
        from main import MainWindow
        from data_manager import DataManager
        main_window = None
        for widget in self.window().findChildren(QWidget):
            if isinstance(widget, MainWindow):
                main_window = widget
                break
                
        # 如果找不到主窗口，使用默认的数据管理器
        if main_window:
            print(f"通过主窗口加载用户票数据: {main_window}")
            tickets = main_window.data_manager.load_user_tickets()
        else:
            # 创建默认数据管理器实例来加载数据
            print("通过默认数据管理器加载用户票数据")
            data_manager = DataManager()
            print(f"数据目录: {data_manager.data_dir}")
            tickets = data_manager.load_user_tickets()
            print(f"加载到的用户票数量: {len(tickets)}")
            
        # 只显示双色球记录
        dcb_tickets = [ticket for ticket in tickets if ticket["type"] == "double色球"]
        print(f"双色球票数量: {len(dcb_tickets)}")
        
        self.user_table.setRowCount(len(dcb_tickets))
        
        for row, ticket in enumerate(dcb_tickets):
            # 设置购买日期为可编辑，并使用自定义的日期编辑器
            date_item = QTableWidgetItem(ticket["date"])
            date_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled)
            self.user_table.setItem(row, 0, date_item)
            
            # 格式化显示号码
            numbers_str = ",".join(map(str, ticket["numbers"][0])) + "+" + str(ticket["numbers"][1])
            numbers_item = QTableWidgetItem(numbers_str)
            numbers_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled)
            self.user_table.setItem(row, 1, numbers_item)
            
            # 添加保存和删除按钮
            button_widget = QWidget()
            button_layout = QHBoxLayout(button_widget)
            button_layout.setContentsMargins(0, 0, 0, 0)
            
            save_btn = QPushButton("保存")
            delete_btn = QPushButton("删除")
            
            # 设置按钮固定宽度
            save_btn.setFixedWidth(50)
            delete_btn.setFixedWidth(50)
            
            # 默认保存按钮不可用
            save_btn.setEnabled(False)
            
            # 连接按钮信号
            save_btn.clicked.connect(lambda checked, r=row: self.save_ticket_editing(r))
            delete_btn.clicked.connect(lambda checked, r=row: self.delete_ticket_by_row(r))
            
            button_layout.addWidget(save_btn)
            button_layout.addWidget(delete_btn)
            
            self.user_table.setCellWidget(row, 2, button_widget)
            # 保存按钮引用以便后续操作
            button_widget.save_btn = save_btn
            
            # 中奖结果显示
            self.user_table.setItem(row, 3, QTableWidgetItem("未匹配"))
        
        # 连接表格单元格双击信号，用于日期选择
        self.user_table.cellDoubleClicked.connect(self.on_ticket_cell_double_clicked)
        # 连接单元格更改信号
        self.user_table.cellChanged.connect(self.on_ticket_cell_changed)
    
    def on_history_cell_changed(self, row, column):
        """处理开奖历史表格单元格更改事件"""
        # 点亮保存按钮
        button_widget = self.history_table.cellWidget(row, 2)
        if button_widget and hasattr(button_widget, 'save_btn'):
            button_widget.save_btn.setEnabled(True)
    
    def on_ticket_cell_changed(self, row, column):
        """处理用户票表格单元格更改事件"""
        # 点亮保存按钮
        button_widget = self.user_table.cellWidget(row, 2)
        if button_widget and hasattr(button_widget, 'save_btn'):
            button_widget.save_btn.setEnabled(True)
    
    def save_history_editing(self, row):
        """保存行编辑结果"""
        # 直接使用DataManager而不是依赖主窗口
        from data_manager import DataManager
        data_manager = DataManager()
        
        try:
            # 获取当前行的数据
            date_item = self.history_table.item(row, 0)
            numbers_item = self.history_table.item(row, 1)
            
            if not date_item or not numbers_item:
                return
                
            date = date_item.text()
            numbers_text = numbers_item.text()
            
            # 解析号码
            numbers_text = numbers_text.replace('，', ',')
            if "+" not in numbers_text:
                raise ValueError("号码格式错误")
                
            parts = numbers_text.split("+")
            if len(parts) != 2:
                raise ValueError("号码格式错误")
                
            red_balls_str = parts[0]
            blue_ball_str = parts[1]
            
            red_balls = [int(x.strip()) for x in red_balls_str.split(",")]
            blue_ball = int(blue_ball_str.strip())
            
            if len(red_balls) != 6:
                raise ValueError("红球号码必须是6个")
                
            # 检查号码范围
            for num in red_balls:
                if num < 1 or num > 33:
                    raise ValueError("红球号码必须在1-33之间")
                    
            if blue_ball < 1 or blue_ball > 16:
                raise ValueError("蓝球号码必须在1-16之间")
            
            # 获取所有历史记录
            history = data_manager.load_lottery_history()
            
            # 查找并更新对应的记录
            for item in history:
                if item["type"] == "double_color_ball" and item["date"] == date:
                    item["numbers"] = [red_balls, blue_ball]
                    break
            
            # 保存更新后的数据
            data_manager.save_lottery_history(history)
            
            # 禁用保存按钮
            button_widget = self.history_table.cellWidget(row, 2)
            if button_widget and hasattr(button_widget, 'save_btn'):
                button_widget.save_btn.setEnabled(False)
                
            QMessageBox.information(self, "保存成功", "开奖记录保存成功")
            
        except ValueError as e:
            QMessageBox.critical(self, "输入错误", f"号码格式错误: {str(e)}")
        except Exception as e:
            QMessageBox.critical(self, "保存失败", f"保存开奖记录时发生错误: {str(e)}")
    
    def save_ticket_editing(self, row):
        """保存票务行编辑结果"""
        # 禁用保存按钮
        button_widget = self.user_table.cellWidget(row, 2)
        if button_widget and hasattr(button_widget, 'save_btn'):
            button_widget.save_btn.setEnabled(False)
        
        # 直接保存数据而不是触发另一个事件
        self._save_ticket_data(row)

    def _save_ticket_data(self, row):
        """实际保存票务数据"""
        from data_manager import DataManager
        data_manager = DataManager()
        
        # 获取更改后的数据
        date_item = self.user_table.item(row, 0)
        numbers_item = self.user_table.item(row, 1)
        
        if not date_item or not numbers_item:
            return
            
        new_date = date_item.text()
        numbers_text = numbers_item.text()
        
        try:
            # 解析号码格式
            numbers_text = numbers_text.replace('，', ',')
            if "+" not in numbers_text:
                raise ValueError("号码格式错误")
                
            parts = numbers_text.split("+")
            if len(parts) != 2:
                raise ValueError("号码格式错误")
                
            red_balls_str = parts[0]
            blue_ball_str = parts[1]
            
            red_balls = [int(x.strip()) for x in red_balls_str.split(",")]
            blue_ball = int(blue_ball_str.strip())
            
            if len(red_balls) != 6:
                raise ValueError("红球号码必须是6个")
                
            # 检查号码范围
            for num in red_balls:
                if num < 1 or num > 33:
                    raise ValueError("红球号码必须在1-33之间")
                    
            if blue_ball < 1 or blue_ball > 16:
                raise ValueError("蓝球号码必须在1-16之间")
            
            # 获取所有票数据并更新对应记录
            tickets = data_manager.load_user_tickets()
            
            # 查找并更新记录
            for ticket in tickets:
                if ticket["type"] == "double_color_ball" and ticket["date"] == new_date:
                    ticket["numbers"] = [red_balls, blue_ball]
                    break
            
            # 保存更新后的数据
            data_manager.save_user_tickets(tickets)
                
        except ValueError as e:
            QMessageBox.critical(self, "输入错误", f"号码格式错误: {str(e)}")
            # 恢复原始数据
            self.user_table.cellChanged.disconnect(self.on_ticket_cell_changed)
            self.refresh_user_table()
            self.user_table.cellChanged.connect(self.on_ticket_cell_changed)
    
    def on_date_cell_changed(self, row, column, date_edit):
        """处理日期单元格更改事件"""
        from PyQt5.QtCore import QDate
        
        # 获取新的日期值
        new_date = date_edit.date().toString("yyyy-MM-dd")
        
        # 更新表格单元格的显示内容
        date_item = QTableWidgetItem(new_date)
        date_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled)
        self.history_table.removeCellWidget(row, column)
        self.history_table.setItem(row, column, date_item)
        
        # 点亮保存按钮而不是直接保存
        button_widget = self.history_table.cellWidget(row, 2)
        if button_widget and hasattr(button_widget, 'save_btn'):
            button_widget.save_btn.setEnabled(True)
    
    def on_history_cell_double_clicked(self, row, column):
        """处理开奖历史表格单元格双击事件，用于日期选择"""
        if column == 0:  # 如果是日期列
            from PyQt5.QtWidgets import QDateEdit
            from PyQt5.QtCore import QDate
            
            # 获取当前日期值
            date_item = self.history_table.item(row, column)
            if date_item:
                current_date = date_item.text()
                try:
                    # 创建日期编辑控件
                    date_edit = QDateEdit()
                    date_edit.setDisplayFormat("yyyy-MM-dd")
                    date_edit.setDate(QDate.fromString(current_date, "yyyy-MM-dd"))
                    date_edit.setCalendarPopup(True)  # 启用日历弹窗
                    
                    # 将日期编辑控件设置为表格单元格的控件
                    self.history_table.setCellWidget(row, column, date_edit)
                    
                    # 连接日期更改信号
                    date_edit.dateChanged.connect(
                        lambda: self.on_date_cell_changed(row, column, date_edit)
                    )
                except Exception as e:
                    print(f"日期格式错误: {e}")
    
    def on_ticket_cell_double_clicked(self, row, column):
        """处理用户票表格单元格双击事件，用于日期选择"""
        if column == 0:  # 如果是日期列
            from PyQt5.QtWidgets import QDateEdit
            from PyQt5.QtCore import QDate
            
            # 获取当前日期值
            date_item = self.user_table.item(row, column)
            if date_item:
                current_date = date_item.text()
                try:
                    # 创建日期编辑控件
                    date_edit = QDateEdit()
                    date_edit.setDisplayFormat("yyyy-MM-dd")
                    date_edit.setDate(QDate.fromString(current_date, "yyyy-MM-dd"))
                    date_edit.setCalendarPopup(True)  # 启用日历弹窗
                    
                    # 将日期编辑控件设置为表格单元格的控件
                    self.user_table.setCellWidget(row, column, date_edit)
                    
                    # 连接日期更改信号
                    date_edit.dateChanged.connect(
                        lambda: self.on_ticket_date_cell_changed(row, column, date_edit)
                    )
                except Exception as e:
                    print(f"日期格式错误: {e}")
    
    def on_ticket_date_cell_changed(self, row, column, date_edit):
        """处理用户票日期单元格更改事件"""
        from PyQt5.QtCore import QDate
        
        # 获取新的日期值
        new_date = date_edit.date().toString("yyyy-MM-dd")
        
        # 更新表格单元格的显示内容
        date_item = QTableWidgetItem(new_date)
        date_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled)
        self.user_table.removeCellWidget(row, column)
        self.user_table.setItem(row, column, date_item)
        
        # 触发数据保存
        self.on_ticket_cell_changed(row, column)
    
    def delete_record(self, date):
        # 使用DataManager直接处理数据而不是依赖主窗口
        from data_manager import DataManager
        data_manager = DataManager()
        
        history = data_manager.load_lottery_history()
        # 过滤掉要删除的记录
        new_history = [item for item in history if not (item["type"] == "double_color_ball" and item["date"] == date)]
        data_manager.save_lottery_history(new_history)
        self.refresh_history_table()
        QMessageBox.information(self, "删除成功", "开奖记录删除成功")
    
    def delete_record_by_row(self, row):
        """根据行号删除记录"""
        # 获取要删除的记录的日期
        date_item = self.history_table.item(row, 0)
        if not date_item:
            return
            
        date = date_item.text()
        self.delete_record(date)
    
    def delete_ticket(self, date):
        # 使用DataManager直接处理数据而不是依赖主窗口
        from data_manager import DataManager
        data_manager = DataManager()
        
        tickets = data_manager.load_user_tickets()
        # 过滤掉要删除的记录（简单按日期过滤，实际应用中可能需要更精确的标识）
        new_tickets = [ticket for ticket in tickets if not (ticket["type"] == "double_color_ball" and ticket["date"] == date)]
        data_manager.save_user_tickets(new_tickets)
        self.refresh_user_table()
        QMessageBox.information(self, "删除成功", "用户号码删除成功")
    
    def delete_ticket_by_row(self, row):
        """根据行号删除票"""
        # 获取要删除的记录的日期
        date_item = self.user_table.item(row, 0)
        if not date_item:
            return
            
        date = date_item.text()
        self.delete_ticket(date)
    
    def match_lottery(self):
        # 使用DataManager直接处理数据而不是依赖主窗口
        from data_manager import DataManager
        from matcher import NumberMatcher
        
        data_manager = DataManager()
        matcher = NumberMatcher()
        
        user_tickets = data_manager.load_user_tickets()
        lottery_history = data_manager.load_lottery_history()
        
        # 只处理双色球
        dcb_tickets = [ticket for ticket in user_tickets if ticket["type"] == "double_color_ball"]
        dcb_history = [history for history in lottery_history if history["type"] == "double_color_ball"]
        
        # 修复匹配逻辑：确保有数据才进行匹配
        if not dcb_tickets or not dcb_history:
            QMessageBox.information(self, "匹配结果", "没有足够的数据进行匹配，请确保已录入开奖历史和用户号码")
            return
            
        results = matcher.match_tickets(dcb_tickets, dcb_history)
        
        # 显示匹配结果对话框
        dialog = MatchResultDialog(results, self)
        dialog.exec_()
        
        # 更新表格中的中奖结果显示
        self.refresh_user_table_with_results(results)
    
    def refresh_user_table_with_results(self, results):
        """
        根据匹配结果更新表格中的中奖结果显示
        """
        for row in range(self.user_table.rowCount()):
            # 获取当前行的日期
            date_item = self.user_table.item(row, 0)
            if not date_item:
                continue
                
            current_date = date_item.text()
            
            # 查找匹配的结果
            result_found = False
            for result in results:
                if result.get('ticket_date') == current_date:
                    # 更新中奖结果显示
                    prize_item = self.user_table.item(row, 3)
                    if prize_item:
                        if "error" in result:
                            prize_item.setText("错误")
                        else:
                            prize_name = result['prize_info']['name']
                            prize_item.setText(prize_name if result['is_winning'] else "未中奖")
                            # 使中奖结果可点击查看详细信息
                            prize_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                    result_found = True
                    break
            
            # 如果没有找到匹配结果，保持原状或设置为"未匹配"
            if not result_found:
                prize_item = self.user_table.item(row, 3)
                if prize_item and prize_item.text() == "":
                    prize_item.setText("未匹配")
        
        # 连接中奖结果单元格点击信号
        self.user_table.cellClicked.connect(self.on_prize_cell_clicked)
    
    def on_prize_cell_clicked(self, row, column):
        """处理中奖结果单元格点击事件"""
        if column == 3:  # 如果是中奖结果列
            prize_item = self.user_table.item(row, 3)
            if prize_item and prize_item.text() not in ["未匹配", ""]:
                # 显示详细信息对话框
                from data_manager import DataManager
                from matcher import NumberMatcher
                
                data_manager = DataManager()
                matcher = NumberMatcher()
                
                user_tickets = data_manager.load_user_tickets()
                lottery_history = data_manager.load_lottery_history()
                
                # 只处理双色球
                dcb_tickets = [ticket for ticket in user_tickets if ticket["type"] == "double_color_ball"]
                dcb_history = [history for history in lottery_history if history["type"] == "double_color_ball"]
                
                if row < len(dcb_tickets):
                    ticket = dcb_tickets[row]
                    # 找到对应的开奖记录
                    matching_history = None
                    for history in dcb_history:
                        if history["date"] == ticket["date"]:
                            matching_history = history
                            break
                    
                    if matching_history:
                        # 计算匹配详情
                        match_result = matcher.check_match(ticket["numbers"], matching_history["numbers"])
                        
                        # 显示详细信息
                        detail_dialog = MatchDetailDialog(ticket, matching_history, match_result, self)
                        detail_dialog.exec_()

class MatchResultDialog(QDialog):
    """
    匹配结果对话框
    """
    def __init__(self, results, parent=None):
        super().__init__(parent)
        self.results = results
        self.init_ui()
    
    def init_ui(self):
        self.setWindowTitle("匹配结果")
        self.resize(500, 300)
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        # 标题
        title = QLabel("双色球中奖匹配结果")
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet("font-size: 16px; font-weight: bold; margin: 10px;")
        layout.addWidget(title)
        
        # 结果显示
        self.result_text = QTextEdit()
        self.result_text.setReadOnly(True)
        
        result_text = ""
        for result in self.results:
            if "error" in result:
                result_text += f"错误: {result['error']}\n"
            else:
                date = result.get('ticket_date', '未知日期')
                prize_name = result['prize_info']['name']
                if result['is_winning']:
                    result_text += f"日期 {date}: 中奖 - {prize_name}\n"
                else:
                    result_text += f"日期 {date}: 未中奖\n"
        
        if not self.results:
            result_text = "没有可匹配的记录"
            
        self.result_text.setText(result_text)
        layout.addWidget(self.result_text)
        
        # 关闭按钮
        close_btn = QPushButton("关闭")
        close_btn.clicked.connect(self.accept)
        layout.addWidget(close_btn)

class MatchDetailDialog(QDialog):
    """
    匹配详情对话框
    """
    def __init__(self, ticket, history, match_result, parent=None):
        super().__init__(parent)
        self.ticket = ticket
        self.history = history
        self.match_result = match_result
        self.init_ui()
    
    def init_ui(self):
        self.setWindowTitle("匹配详情")
        self.resize(400, 250)
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        # 标题
        title = QLabel("详细匹配信息")
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet("font-size: 16px; font-weight: bold; margin: 10px;")
        layout.addWidget(title)
        
        # 日期信息
        date_label = QLabel(f"购买日期: {self.ticket['date']}")
        layout.addWidget(date_label)
        
        # 号码信息
        ticket_numbers = ",".join(map(str, self.ticket["numbers"][0])) + "+" + str(self.ticket["numbers"][1])
        ticket_label = QLabel(f"购买号码: {ticket_numbers}")
        layout.addWidget(ticket_label)
        
        winning_numbers = ",".join(map(str, self.history["numbers"][0])) + "+" + str(self.history["numbers"][1])
        winning_label = QLabel(f"开奖号码: {winning_numbers}")
        layout.addWidget(winning_label)
        
        # 匹配结果
        match_info = QLabel(f"匹配结果: 红球匹配{self.match_result['red_matches']}个, 蓝球匹配{'是' if self.match_result['blue_match'] else '否'}")
        layout.addWidget(match_info)
        
        # 中奖信息
        prize_label = QLabel(f"中奖等级: {self.match_result['prize']['name']}")
        layout.addWidget(prize_label)
        
        # 奖金信息
        if self.match_result['is_winning']:
            prize_money = QLabel(f"预计奖金: {self.match_result['prize']['prize']}")
            layout.addWidget(prize_money)
        
        # 关闭按钮
        close_btn = QPushButton("关闭")
        close_btn.clicked.connect(self.accept)
        layout.addWidget(close_btn)
